import {
  LoadingOutlined,
  MessageOutlined,
  PlusOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  Avatar,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Image,
  Input,
  Modal,
  Row,
  Space,
  Upload,
  message,
} from 'antd';
import { UploadChangeParam, UploadFile, UploadProps } from 'antd/es/upload';
import { useEffect, useRef, useState } from 'react';
import { getPosts,postAddPosts, postAdd_view, getViews } from '../Register/service';

const { Search } = Input;
const Bbs = (props) => {
  const info = JSON.parse(window.localStorage.getItem('info'))
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isComment, setIsComment] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);
  const [picture, setPicture] = useState([]);
  const [fileList, setFileList] = useState<UploadFile[]>([
    
  ]);
  const [form] = Form.useForm()
  const [postsList,setPostsList] = useState([])
  const [value,setValue] = useState('')
  const valRef = useRef()
  const [refreshCount,setRefreshCount] = useState(0)

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.onload = () => {
      console.log(picture)
      const Base64Data = reader.result;
      setPicture([...picture,Base64Data]);
    };
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
    
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true); 
      console.log(info);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
    
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const showModal = () => {
    setIsModalOpen(true);
  };


  const handleCancel = () => {
    setIsModalOpen(false);
  };


  const fetchPosts = async () => {
    const result = await getPosts({pageNum:1});
    if (result.state === 200) {
       console.log(result.data)
      for(const i of result.data){
       const res = await getViews({
        aid:i?.aid
       })
       if(res.state === 200){
        i.test = res.data
       }
      }
      console.log(result.data)
      setPostsList(result.data)
    }
  };

  useEffect(() => {
    fetchPosts();
  },[refreshCount]);

  return (
    <PageContainer ghost>
      <Row>
        <Col span={16}>
          <Search placeholder="请输入内容进行搜索" allowClear />
        </Col>
        <Col offset={1}>
          <Button type="primary" onClick={showModal}>
            发布帖子
          </Button>
        </Col>
      </Row>
      <div>
        {
          postsList?.map((x,idx) => {
            return(
              <Card key={idx} style={{ width: '100%', marginTop: '20px' }}>
              <div style={{ fontSize: '22px' }}>{x?.title}</div>
              <div>
                <Space>
                  {
                    JSON.parse(x?.picture)?.map((item,idx) => {
                      return(
                        <Image
                        key={idx}
                        width={150}
                        src={item}
                        placeholder={
                          <Image
                            preview={false}
                            src={item}
                            width={150}
                          />
                        }
                      />
                      )
                    })
                  }
                </Space>
              </div>
              <div style={{ position: 'relative', height: '60px' }}>
                  <div style={{ width: '220px', position: 'absolute', right: '0' }}>
                    <Space>
                      <Input
                        placeholder="请输入内容"
                        style={{ width: '150px' }}
                        autoFocus
                        ref={valRef}
                      />
                      <Button onClick={async () => {
                        // console.log(valRef?.current?.input?.value)
                        const result = await postAdd_view({
                          aid:x?.aid,
                          uid:window.localStorage.getItem('token'),
                          view:valRef?.current?.input?.value,
                          issueUser:info?.username
                        })
                        if(result.state === 200){
                          message.success('评论成功')
                          valRef.current.input.value = ''
                          setRefreshCount(refreshCount + 1)
                        }
                      }}>发送</Button>
                    </Space>
                    <div style={{ textAlign: 'right' }}>
                      {/* <a onClick={() => setIsComment(false)}>取消发送</a> */}
                    </div>
                  </div>
            
              </div>
              <Divider>所有评论</Divider>
              {
                x?.test?.map((item,idx) => {
                  return(
                    <div style={{ marginTop: '10px' }} key={idx}>
                    <Row>
                      <Col>
                        <Avatar size="small" icon={<UserOutlined />} />
                      </Col>
                      <Col style={{ marginLeft: '5px' }}>{item?.issueUser}</Col>
                    </Row>
                    <div>
                      {item?.view}
                    </div>
                  </div>
                  )
                })
              }
              {/* <div style={{ marginTop: '10px' }}>
                <Row>
                  <Col>
                    <Avatar size="small" icon={<UserOutlined />} />
                  </Col>
                  <Col style={{ marginLeft: '5px' }}>杨开</Col>
                </Row>
                <div>
                  房间看了电视剧弗兰克的手机发了肯德基弗兰克的手机发了看电视的司法解释离开房间里看书的数量都放假啦是大家放松大家flaked累计收到发送到三点六块腹肌轮快速的减肥就开始了短发就哭了多少积分
                </div>
              </div>
              <div style={{ marginTop: '10px' }}>
                <Row>
                  <Col>
                    <Avatar size="small" icon={<UserOutlined />} />
                  </Col>
                  <Col style={{ marginLeft: '5px' }}>杨开</Col>
                </Row>
                <div>
                  房间看了电视剧弗兰克的手机发了肯德基弗兰克的手机发了看电视的司法解释离开房间里看书的数量都放假啦是大家放松大家flaked累计收到发送到三点六块腹肌轮快速的减肥就开始了短发就哭了多少积分
                </div>
              </div> */}
            </Card>
            )
          })
        }
      </div>
      <Modal
        title="发布帖子"
        open={isModalOpen}
        onOk={async () => {
          const params = form.getFieldsValue()
          if(params){
            const result = await postAddPosts({
              ...params,
              picture:JSON.stringify(picture),
              created_user : info?.username,
              modified_user:info?.username,
              uid:window.localStorage.getItem('token')
            })
            if(result.state === 200){
              message.success('发布成功')
              setIsModalOpen(false)
              setRefreshCount(refreshCount + 1)
            }
            console.log(result)
          }
          form.submit()
        }}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          form={form}
          // onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入内容" />
          </Form.Item>

          <Form.Item label="图片" valuePropName="picture1">
            <Upload
              name="picture1"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // fileList={fileList}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
             {picture.length >= 4 ? null : uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Bbs;
